﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using whatpricemyhouse.LINQ;
using System.Web.Security;
using whatpricemyhouse.Controller;

namespace whatpricemyhouse.agent
{
    public partial class RespondToLead : System.Web.UI.Page
    {

        public String emailId = Guid.NewGuid().ToString();
        public String buyerid = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.User.Identity.IsAuthenticated)
            {
                if (!String.IsNullOrEmpty(Request.QueryString["buyerid"]))
                {
                    buyerid = Request.QueryString["buyerid"];
                    ImageButton ImageButton1 = this.LoginView1.FindControl("ImageButton1") as ImageButton;
                    ImageButton1.Attributes.Add("onmouseover", "mouseOver1(this);");
                    ImageButton1.Attributes.Add("onmouseout", "mouseOut1(this);");
                    ImageButton ImageButton2 = this.LoginView1.FindControl("ImageButton2") as ImageButton;
                    ImageButton2.Attributes.Add("onmouseover", "mouseOver2(this);");
                    ImageButton2.Attributes.Add("onmouseout", "mouseOut2(this);");

                    LoadData(Request.QueryString["buyerid"]);
                }
                else
                {
                    Response.Redirect("~/Agent/BuyerList.aspx?old=1");
                }
            }
        }
        DataControllerDataContext dcdc = new DataControllerDataContext();

        private void LoadData(String buyerid)
        {
            Label nameLabel = this.LoginView1.FindControl("nameLabel") as Label;
            TextBox emailBodyTxt = this.LoginView1.FindControl("emailBodyTxt") as TextBox;
            TextBox signatureTxt = this.LoginView1.FindControl("signatureTxt") as TextBox;
            String customerEmail = "";

            //buy request infotmation
            Label PostcodeLabel = this.LoginView1.FindControl("PostcodeLabel") as Label;
            Label AddressLabel = this.LoginView1.FindControl("AddressLabel") as Label;
            Label BuyerNameLabel = this.LoginView1.FindControl("BuyerNameLabel") as Label;
            Label EmailLabel = this.LoginView1.FindControl("EmailLabel") as Label;
            Label PhoneLabel = this.LoginView1.FindControl("PhoneLabel") as Label;
            Label PriceFromLabel = this.LoginView1.FindControl("PriceFromLabel") as Label;
            Label PriceToLabel = this.LoginView1.FindControl("PriceToLabel") as Label;
            Label PropertyTypeLabel = this.LoginView1.FindControl("PropertyTypeLabel") as Label;
            Label WhenToBuyLabel = this.LoginView1.FindControl("WhenToBuyLabel") as Label;
            Label DateReceivedLabel = this.LoginView1.FindControl("DateReceivedLabel") as Label;

            var buyers = from b in dcdc.buy_request_tables
                         where b.BRID == buyerid
                         select b;
            int i = 0;
            foreach (var buyer in buyers)
            {
                nameLabel.Text = "Dear " + buyer.customer_table.CName;
                customerEmail = buyer.customer_table.CEmail;
                EmailLabel.Text = buyer.customer_table.CEmail;
                PostcodeLabel.Text = buyer.suburb.postcode;
                AddressLabel.Text = buyer.suburb.suburb1;
                BuyerNameLabel.Text = buyer.customer_table.CName;
                PhoneLabel.Text = buyer.customer_table.CPhone;
                PriceFromLabel.Text = buyer.price_range_table.PRName;
                PriceToLabel.Text = buyer.price_range_table1.PRName;
                PropertyTypeLabel.Text = buyer.property_type_table.PTName;
                WhenToBuyLabel.Text = buyer.when_to_buy.WTBName;
                DateReceivedLabel.Text = buyer.createdDate.Value.ToString();
                i++;
                break;
            }
            if (i == 0) {
                Response.Redirect("~/Agent/BuyerList.aspx?old=1");
            }
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            //send email
            Label MessageShow = this.LoginView1.FindControl("MessageShow") as Label;
            if (createEmail())
            {
                var emailList = from ee in dcdc.email_tables
                                where ee.EmailID == emailId
                                select ee;

                foreach (var email in emailList)
                {
                    SendEmail sendMail = new SendEmail(email.email_from, email.email_to, email.email_subject, email.email_body);
                    MessageShow.Text = "Your EMAIL has been sent.";
                    var buyers = from b in dcdc.buy_request_tables
                                 where b.BRID == buyerid
                                 select b;
                    foreach (var buyer in buyers) {
                        buyer.visa += 1;
                        dcdc.SubmitChanges();
                    }
                    break;
                }
            }
            else
            {
                return;
            }
        }

        //create a email
        private bool createEmail()
        {
            TextBox emailBodyTxt = this.LoginView1.FindControl("emailBodyTxt") as TextBox;
            TextBox signatureTxt = this.LoginView1.FindControl("signatureTxt") as TextBox;
            TextBox summaryTxt = this.LoginView1.FindControl("summaryTxt") as TextBox;
            //get email template
            var email_templates = from temp in dcdc.template_tables
                                  where temp.name == "email"
                                  select temp;

            String email_template = "";
            foreach (var temp in email_templates)
            {
                email_template = temp.htmlcode;
            }

            email_table et = new email_table();
            et.EmailID = emailId;

            Label EmailLabel = this.LoginView1.FindControl("EmailLabel") as Label;
            et.email_to = EmailLabel.Text;
            et.BRID = Request.QueryString["buyerid"];
            MembershipUser user = Membership.GetUser(Page.User.Identity.Name);
            et.email_from = user.Email;
            et.UserID = new Guid(user.ProviderUserKey.ToString());
            et.send_date = DateTime.Now.ToString();
            et.email_subject = "Respond to Lead..";

            var agent = (from a in dcdc.agent_info_tables
                         where a.UserID == et.UserID
                         select a).Single();

            email_template = email_template.Replace("@host@", Request.Url.Authority);
            email_template = email_template.Replace("@agent_photo@", agent.Photo.Replace("../images/agentPhotos/",""));
            email_template = email_template.Replace("@phone@", agent.Phone);
            email_template = email_template.Replace("@moblie@", agent.Mobile);
            email_template = email_template.Replace("@Facsimile@", agent.Fax);
            email_template = email_template.Replace("@body@", emailBodyTxt.Text + "<br />" + signatureTxt.Text + "<br />" + summaryTxt.Text);

            MarketComparisonsSelector mcs1 = this.LoginView1.FindControl("marketComparisonsSelector1") as MarketComparisonsSelector;
            MarketComparisonsSelector mcs2 = this.LoginView1.FindControl("marketComparisonsSelector2") as MarketComparisonsSelector;
            MarketComparisonsSelector mcs3 = this.LoginView1.FindControl("marketComparisonsSelector3") as MarketComparisonsSelector;

            bool save1 = false;
            bool save2 = false;
            bool save3 = false;
            email_show_property_list_table esplt1 = new email_show_property_list_table();
            esplt1.EmailID = emailId;
            esplt1.propertyID = mcs1.getSelectedValue();
            if (mcs1.getSelectedValue() != "1")
            {
                save1 = true;
                var property = (from p in dcdc.market_comparison_property_tables
                                where p.propertyID == mcs1.getSelectedValue()
                                select p).Single();

                email_template = email_template.Replace("@no1@", property.no.ToString());
                email_template = email_template.Replace("@sale_image1@", property.imageUrl.Replace("../images/button/", ""));
                email_template = email_template.Replace("@place1@", property.suburb.suburb1);
                email_template = email_template.Replace("@streetNum1@", property.streetNum);
                email_template = email_template.Replace("@address1@", property.address);
                email_template = email_template.Replace("@time1@", property.dateOfSale.Value.ToString());
                email_template = email_template.Replace("@Price1@", "$" + property.price);
            }
            else
            {
                email_template = email_template.Replace("@no1@", "");
                email_template = email_template.Replace("@sale_image1@", "");
                email_template = email_template.Replace("@place1@", "");
                email_template = email_template.Replace("@streetNum1@", "");
                email_template = email_template.Replace("@address1@", "");
                email_template = email_template.Replace("@time1@", "");
                email_template = email_template.Replace("@Price1@", "");
            }

            email_show_property_list_table esplt2 = new email_show_property_list_table();
            esplt2.EmailID = emailId;
            esplt2.propertyID = mcs2.getSelectedValue();
            if (mcs2.getSelectedValue() != "1")
            {
                save2 = true;
                var property = (from p in dcdc.market_comparison_property_tables
                                where p.propertyID == mcs2.getSelectedValue()
                                select p).Single();

                email_template = email_template.Replace("@no2@", property.no.ToString());
                email_template = email_template.Replace("@sale_image2@", property.imageUrl.Replace("../images/button/", ""));
                email_template = email_template.Replace("@place2@", property.suburb.suburb1);
                email_template = email_template.Replace("@streetNum2@", property.streetNum);
                email_template = email_template.Replace("@address2@", property.address);
                email_template = email_template.Replace("@time2@", property.dateOfSale.Value.ToString());
                email_template = email_template.Replace("@Price2@", "$" + property.price);
            }
            else
            {
                email_template = email_template.Replace("@no2@", "");
                email_template = email_template.Replace("@sale_image2@", "");
                email_template = email_template.Replace("@place2@", "");
                email_template = email_template.Replace("@streetNum2@", "");
                email_template = email_template.Replace("@address2@", "");
                email_template = email_template.Replace("@time2@", "");
                email_template = email_template.Replace("@Price2@", "");
            }
            email_show_property_list_table esplt3 = new email_show_property_list_table();
            esplt3.EmailID = emailId;
            esplt3.propertyID = mcs3.getSelectedValue();
            if (mcs3.getSelectedValue() != "1")
            {
                save3 = true;
                var property = (from p in dcdc.market_comparison_property_tables
                                where p.propertyID == mcs3.getSelectedValue()
                                select p).Single();

                email_template = email_template.Replace("@no3@", property.no.ToString());
                email_template = email_template.Replace("@sale_image3@", property.imageUrl.Replace("../images/button/",""));
                email_template = email_template.Replace("@place3@", property.suburb.suburb1);
                email_template = email_template.Replace("@streetNum3@", property.streetNum);
                email_template = email_template.Replace("@address3@", property.address);
                email_template = email_template.Replace("@time3@", property.dateOfSale.Value.ToString());
                email_template = email_template.Replace("@Price3@", "$" + property.price);
            }
            else
            {
                email_template = email_template.Replace("@no3@", "");
                email_template = email_template.Replace("@sale_image3@", "");
                email_template = email_template.Replace("@place3@", "");
                email_template = email_template.Replace("@streetNum3@", "");
                email_template = email_template.Replace("@address3@", "");
                email_template = email_template.Replace("@time3@", "");
                email_template = email_template.Replace("@Price3@", "");
            }
            et.email_body = email_template;
            dcdc.email_tables.InsertOnSubmit(et);
            if (save1)
            {
                dcdc.email_show_property_list_tables.InsertOnSubmit(esplt1);
            }
            if (save2)
            {
                dcdc.email_show_property_list_tables.InsertOnSubmit(esplt2);
            }

            if (save3)
            {
                dcdc.email_show_property_list_tables.InsertOnSubmit(esplt3);
            }
            dcdc.SubmitChanges();

            return true;
        }

        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            //send email
            if (createEmail())
            {
                Label MessageShow = this.LoginView1.FindControl("MessageShow") as Label;
                MessageShow.Text = "<a href=''><script>window.open('EmailPreview.aspx?emailid=" + emailId + "')</script></a>";
                //Response.Write("<script>window.open('EmailPreview.aspx?emailid=" + emailId + "')</script>");
            }
            else
            {
                return;
            }
        }

    }
}